package cn.bsuc.crm.service.impl;

import cn.bsuc.crm.dto.CustomerDTO;
import cn.bsuc.crm.entity.Customer;
import cn.bsuc.crm.mapper.CustomerMapper;
import cn.bsuc.crm.service.CustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhuoyuan
 * @since 2022-10-03
 */
@Service
public class CustomerServiceImp extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public PageInfo<Customer> getPage(Customer customer,int pageNo, int pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        List<Customer> list = customerMapper.selectByParams(customer);
        PageInfo<Customer> page = new PageInfo<>(list);
        return page;

//        PageInfo<Customer> customerPage = new Page<>(customerDTO.getPageNo(),customerDTO.getPageSize());
//        PageInfo<Customer> selectPage = customerMapper.selectPage(customerPage, null);
//        return selectPage;
    }

    /*
       添加和修改
     * 1. 设置参数的默认值
     *      是否有效 isValid    1
     *      创建时间 createDate 系统当前时间
     *      修改时间 updateDate 系统当前时间
     *      流失状态 state      0
     *          0=正常客户  1=流失客户
     *      客户编号 khno
     *          系统生成，唯一 （uuid | 时间戳 | 年月日时分秒 | 雪花算法）
     *          格式：KH + 时间戳
     *  1. 执行添加操作，判断受影响的行数
     * */
    @Override
    public int saveCustomer(Customer customer) {
        if (customer.getId() == null) {
            customer.setIsValid(1);
            customer.setCreateDate(LocalDateTime.now());
            customer.setUpdateDate(LocalDateTime.now());
            customer.setState(0);

        //生成客户编号
            String khno = "KH" + System.currentTimeMillis();
            customer.setKhno(khno);

            int insert = customerMapper.insert(customer);
            return insert;
        } else {
            customer.setUpdateDate(LocalDateTime.now());
            int i = customerMapper.updateById(customer);
            return i;
        }
    }

//    根据id删除
    @Override
    public int deleteById(Integer id) {
        int del = customerMapper.deleteById(id);
        return del;
    }
// 根据id查询
    @Override
    public Customer selectById(Integer id) {
        Customer customer = customerMapper.selectById(id);
        return customer;
    }


}
